<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class Image extends Model
{
    const PRODUCT_COVER = 1;
    const PRODUCT_IMAGES = 2;
    const SKU_COVER = 3;
    const CATEGORY_COVER = 4;
    const COUPON = 5;
    const CAROUSEL = 6;
    const NOTICE = 7;
    const CUSTOMER_AVATAR = 8;

    protected $fillable = [
        'type',
        'type_id',
        'checksum',
        'host',
        'path'
    ];

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            if (!$model->host) {
                $model->host = getHostFromFullPath(Storage::disk(config('filesystems.upload'))->url($model->path));
            }

            if (!$model->id) {
                $model->checksum = md5_file(Storage::disk(config('filesystems.upload'))->url($model->path));
            }
        });
    }

    public function getSrcAttribute()
    {
        return trim($this->host, '/') . '/' . ltrim($this->path, '/');
    }
}
